/**
 * 全局的utils方法
 * @author baoya
 * @since 1.1.0
 * {@link Utils.cflagClick} 绑定事件，用户只要在button a 等后面协商这个标签 cflag:delete
 * {@link getSimpleJson} 与服务器交互
 * {@link getUrlParams} 获取路由后面的参数
 * {@link formatParams} 将路由后面的数据格式化
 */

function getMap() {
    var map = new Map();
    map.set(1001, "请登录后访问");
    map.set(1002, "用户登录异常");
    map.set(1003, "当前用户不存在");
    map.set(1004, "账户名或手机号、密码不能为空");
    map.set(1005, "用户名或密码错误");
    map.set(1006, "注册失败");
    return map;
}


var Utils = {

        logOut: function () {
            new Vue({
                el: "#logOut",
                computed: {
                    logOut: function () {
                        return "        <div class='header-top-area'>" +
                            "            <div class='container-fluid'>" +
                            "                <div class='row'>" +
                            "                    <div class='col-lg-12 col-md-12 col-sm-12 col-xs-12'>" +
                            "                        <div class='header-top-wraper'>" +
                            "                            <div class='row'>" +
                            "                                <div class='col-lg-1 col-md-0 col-sm-1 col-xs-12'>" +
                            "                                    <div class='menu-switcher-pro'>" +
                            "                                        <button type='button' id='sidebarCollapse'" +
                            "                                                class='btn bar-button-pro header-drl-controller-btn btn-info navbar-btn'>" +
                            // "                                            <i class='educate-icon educate-nav'></i>" +
                            "                                        </button>" +
                            "                                    </div>" +
                            "                                </div>" +
                            "                                <div class='col-lg-6 col-md-7 col-sm-6 col-xs-12'>" +
                            "                                    <div class='header-top-menu tabl-d-n'>" +
                            "                                        <ul class='nav navbar-nav mai-top-nav'>" +
                            // "                                            <li class='nav-item'><a href='index.html' class='nav-link'>Home</a></li>" +
                            "                                        </ul>" +
                            "                                    </div>" +
                            "                                </div>" +
                            "                                <div class='col-lg-5 col-md-5 col-sm-12 col-xs-12'>" +
                            "                                    <div class='header-right-info'>" +
                            "                                        <ul class='nav navbar-nav mai-top-nav header-right-menu'>" +
                            "                                            <li class='nav-item'>" +
                            "                                                <a href='#' data-toggle='dropdown' role='button' aria-expanded='false'" +
                            "                                                   class='nav-link dropdown-toggle'>" +
                            "                                                    <img src='img/logo/headimg.png' alt=''/>" +
                            "                                                    <span class='admin-name'></span>" +
                            "                                                    <i class='fa fa-angle-down edu-icon edu-down-arrow'></i>" +
                            "                                                </a>" +
                            "                                                <ul role='menu'" +
                            "                                                    class='dropdown-header-top author-log dropdown-menu animated zoomIn'>" +
                            "                                                    <li><a href='javascript:void(0)' onclick='Utils.logout()'><span" +
                            "                                                            class='edu-icon edu-locked author-log-ic'></span>退出</a>" +
                            "                                                    </li>" +
                            "                                                </ul>" +
                            "                                            </li>" +
                            "                                        </ul>" +
                            "                                    </div>" +
                            "                                </div>" +
                            "                            </div>" +
                            "                        </div>" +
                            "                    </div>" +
                            "                </div>" +
                            "            </div>" +
                            "        </div>";
                    }
                }
            })
        },
        //页面数据加载
        loadPage: function () {
            new Vue({
                el: '#load-page',
                data: {},
                computed: {
                    loadPage: function () {
                        return "    <nav id='sidebar' class=''> " +
                            "        <div class='sidebar-header'>" +
                            "            <a href='index.html'><img class='main-logo' src='img/logo/logo.png' alt='公司头像'/></a> " +
                            "            <strong><a href='index.html'><img src='img/logo/logosn.png' alt=''/></a></strong> " +
                            "        </div> " +
                            "        <div class='left-custom-menu-adp-wrap comment-scrollbar'> " +
                            "            <nav class='sidebar-nav left-sidebar-menu-pro'> " +
                            "                <ul class='metismenu' id='menu1'> " +
                            // "                    <li class='active'> " +
                            // "                        <a class='has-arrow' href='javascript:void(0)'> " +
                            // "                            <span class='educate-icon educate-student icon-wrap'></span> " +
                            // "                            <span class='mini-click-non'>简历</span> " +
                            // "                        </a> " +
                            // "                        <ul class='submenu-angle' aria-expanded='true'> " +
                            // "                            <li><a title='文章列表' href='resumeListMgt.html'><span class='mini-sub-pro'>简历列表</span></a></li> " +
                            // "                            <li><a title='面试情况' href='interviewMgtList.html'><span class='mini-sub-pro'>面试情况</span></a></li> " +
                            // "                        </ul> " +
                            // "                    </li> " +
                            "                    <li class='active'> " +
                            "                        <a class='has-arrow' href='javascript:void(0)'> " +
                            "                            <span class='educate-icon educate-student icon-wrap'></span> " +
                            "                            <span class='mini-click-non'>联系我们</span> " +
                            "                        </a> " +
                            "                        <ul class='submenu-angle' aria-expanded='true'> " +
                            "                            <li><a title='文章列表' href='contactListMgt.html'><span class='mini-sub-pro'>联系人列表</span></a></li> " +
                            "                        </ul> " +
                            "                    </li> " +
                            "                    <li class='active'> " +
                            "                        <a class='has-arrow' href='javascript:void(0)'> " +
                            "                            <span class='educate-icon educate-pages icon-wrap'></span> " +
                            "                            <span class='mini-click-non'>文章目录</span> " +
                            "                        </a> " +
                            "                        <ul class='submenu-angle' aria-expanded='true'> " +
                            "                            <li><a title='文章列表' href='articleCatalogMgt.html'><span class='mini-sub-pro'>文章列表</span></a></li> " +
                            // "                            <li><a title='文章浏览次数' href='browserArticleListMgt.html'><span class='mini-sub-pro'>浏览详情</span></a></li> " +
                            "                            <li><a title='文章评价' href='evaluateMgtList.html'><span class='mini-sub-pro'>文章评价</span></a></li> " +
                            // "                            <li><a title='文章评论' href='commentListMgt.html'><span class='mini-sub-pro'>文章评论</span></a></li> " +
                            "                        </ul> " +
                            "                    </li> " +
                            "                    <li class='active'> " +
                            "                        <a title='文件操作' class='has-arrow' href='javascript:void(0)'> " +
                            "                            <span class='educate-icon educate-library icon-wrap'></span> " +
                            "                            <span class='mini-click-non'>文件操作</span></a> " +
                            "                        <ul class='submenu-angle' aria-expanded='true'> " +
                            "                            <li><a title='文件操作' href='attachListMgt.html'><span class='mini-sub-pro'>文件列表</span></a></li> " +
                            "                        </ul> " +
                            "                    </li> " +
                            "                    <li class='active'> " +
                            "                        <a title='框架' class='has-arrow' href='javascript:void(0)'> " +
                            "                            <span class='educate-icon educate-info icon-wrap'></span> " +
                            "                            <span class='mini-click-non'>框架</span></a> " +
                            "                        <ul class='submenu-angle' aria-expanded='true'> " +
                            "                            <li><a title='框架下载次数' href='uploadDownloadRecordListMgt.html'><span class='mini-sub-pro'>下载次数</span></a></li> " +
                            "                        </ul> " +
                            "                    </li> " +
                            "                    <li class='active'> " +
                            "                        <a title='网站' class='has-arrow' href='javascript:void(0)'> " +
                            "                            <span class='educate-icon educate-apps icon-wrap'></span> " +
                            "                            <span class='mini-click-non'>网站基础</span></a> " +
                            "                        <ul class='submenu-angle' aria-expanded='true'> " +
                            "                            <li><a title='浏览次数' href='websiteBrowseNums.html'><span class='mini-sub-pro'>浏览次数</span></a></li> " +
                            "                        </ul> " +
                            "                    </li> " +
                            "                </ul> " +
                            "            </nav> " +
                            "        </div> " +
                            "    </nav> ";
                    }
                }
            });
        },
        //页面事件绑定
        cflagClick: function () {
            $("*[cflag]").unbind("click");
            $("body").on("click", "*[cflag]", function (e) {
                if (!$(this).is(".not-stopPropagation")) {
                    e.stopPropagation();
                }
                var target = $(e.target);
                if (!target.parents(".onoffswitch").length) { //过滤掉switch组件
                    if ($(this).is("[rightWin=true]") && $(".lgm-common-win-right").length && !$(this).parents("*[op=true]").length) {
                    } else {
                        var cid = $(this).attr("cid");
                        if (cid) {
                            fns[$(this).attr("cflag")](cid, $(this));
                        } else {
                            fns[$(this).attr("cflag")]($(this));
                        }
                    }
                }
            });
        },

        //提交参数时的时间处理
        paramsDateHandle: function (obj) {
            if (obj) {
                for (var key in obj) {
                    var item = obj[key];
                    var regDay = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/,
                        regHour = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d)$/,
                        regMin = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d$/;
                    if (regDay.test(item)) {
                        obj[key] = item + " 00:00:00";
                    } else if (regHour.test(item)) {
                        obj[key] = item + ":00:00";
                    } else if (regMin.test(item)) {
                        obj[key] = item + ":00";
                    }
                }
                return obj;
            } else {
                alert("请为Utils.paramsDateHandle方法提供参数！");
            }
        },

        //系统中常用的简单的获取json数据的请求
        //var obj = {params: {}, url: "",fn: ,noAsync: error, type: "" , noLayer: false, noErrMsg: false}
        getSimpleJson: function (obj) {
            if (obj) {
                if (!obj.noLayer) {
                    obj.index = layer.load("loading...", 3);
                }
                obj.urlFlag = (obj.url.indexOf(".json") > -1 || obj.url.indexOf("http://") > -1 || obj.url.indexOf("https://") > -1);
                obj.url = (obj.url ? (obj.urlFlag ? obj.url : (constant.server_path + obj.url)) : "");
                this.ajax(obj);
            } else {
                layer.msg("请配置参数", {time: 1000, icon: 2});
            }
        },

        /**
         * 参数包括 url，id
         * @param params={url:"",id:""}
         */
        delete: function (params) {
            $.ajax({
                url: constant.server_path + params.url,
                async: false,
                dataType: 'json',
                timeout: 3000,
                type: "POST",
                crossDomain: true,
                data: {
                    _method: "DELETE", //这里是要修改的部分
                    id: params['id'],
                },
                xhrFields: {
                    withCredentials: true
                },
                cache: false,
                success: function () {
                    if (data.success) {
                        layer.msg("删除成功", {time: 800, icon: 1}, function () {
                            fns.search();
                        });
                    } else {
                        layer.msg(data.errorCtx.errorMsg, {time: 2000, icon: 2});
                    }

                },
                fail: function (data) {
                    Utils.failCallback(data)
                }
            });
        },
        //获取请求头信息
        getHeaders: function () {
            var header = {};
            $.ajax({
                url: constant.server_path + "/manager/index",
                async: false,
                dataType: 'json',
                timeout: 3000,
                type: "GET",
                crossDomain: true,
                xhrFields: {
                    withCredentials: true
                },
                cache: false,
                //这个会导致调用一次，但会返回两个接口。
                // contentType: 'application/text; charset=utf-8;',
                success: function (data, status, xhr) {
                    $(".admin-name").text(xhr.getResponseHeader('name'));
                },
                fail: function (data) {
                }
            });
            return header;
        },

        /**
         * 失败回调
         * @param obj
         * @param data
         */
        failCallback: function (data) {
            var map = getMap();
            let key = data.status;
            if (map.has(key)) {
                layer.msg(map.get(key), {time: 2000, icon: 2}, function () {
                    window.location.href = "index.html";
                });
            } else {
                layer.msg("接口报错了，请检查！！！<br>" + this.url, {time: 2000, icon: 2});
            }
        },

        //封装ajax
        //var obj = {type: "", params:{},url: "", fn: , noAsync: , error:,}
        ajax: function (obj) {
            $.ajax({
                    cache: false,
                    type: (obj.type ? obj.type : "GET"),
                    crossDomain: true,
                    data: Utils.paramsDateHandle($.extend((obj.params ? obj.params : {}), constant.commonParams)),
                    url: obj.url,
                    dataType: "json",
                    xhrFields: {
                        withCredentials: true
                    },
                    async: (obj.noAsync ? false : true),
                    success: function (data) {
                        if (!obj.noLayer) {
                            layer.close(obj.index);
                        }
                        if (data.success) {
                            if (obj.fn && (typeof obj.fn == "function")) {
                                obj.fn(data.resultData, data);
                            }
                        } else {
                            if (data.errorCtx) {
                                let code = data.errorCtx.errorCode;
                                if (code == '0002') {
                                    window.location.href = "500.html";
                                } else {
                                    layer.msg(data.errorCtx.errorMsg, {time: 2000, icon: 2}, function () {
                                        window.location.href = "login.html";
                                    });
                                }
                            }
                        }
                    },
                    error:
                        function (data, status, xhr) {
                            if (!obj.noLayer) {
                                layer.close(obj.index);
                            }
                            Utils.failCallback(data);
                        }
                }
            )
            ;
        },

//获取url路径中的参数
        getUrlParams: function (url) {
            url = url ? url : window.location.href;
            var obj = {};
            if (url.indexOf("?") > -1) {
                url = url.split("?");
                url = url[url.length - 1].split("&");
                for (var i = 0; i < url.length; i++) {
                    var item = url[i];
                    var param = item.split("=");
                    if (obj[param[0]]) {
                        if (obj[param[0]] instanceof Array) {
                            obj[param[0]].push(param[1]);
                        } else {
                            var arr = [];
                            arr.push(obj[param[0]]);
                            arr.push(param[1]);
                            obj[param[0]] = arr;
                        }
                    } else {
                        obj[param[0]] = param[1];
                    }
                }
            } else {
                console.log("此url:" + url + "无参数");
            }
            return obj;
        },

        /**
         * 初始化summernote
         */
        initSummernote: function () {
            $("#articleContent").summernote({
                height: 400,
                focus: true,
                lang: 'zh-CN', //设置中文，需引入中文插件summernote-zh-CN.js
                placeholder: '请输入信息。。。.', //占位符
                toolbar: [
                    ['fontname', ['fontname']],
                    ['style', ['bold', 'italic', 'underline', 'clear']],
                    ['font', ['strikethrough', 'superscript', 'subscript']], //字体划线、字体上标、字体下标
                    ['fontsize', ['fontsize']], //字体大小
                    ['color', ['color']], //字体颜色
                    ['style', ['style']],//样式
                    ['para', ['ul', 'ol', 'paragraph']], //无序列表、有序列表、段落对齐方式
                    ['height', ['height']], //行高
                    ['table', ['table']], //插入表格
                    ['hr', ['hr']],//插入水平线
                    ['link', ['link']], //插入链接
                    ['picture', ['picture']], //插入图片
                    ['video', ['video']], //插入视频
                    ['fullscreen', ['fullscreen']], //全屏
                    ['codeview', ['codeview']], //查看html代码
                    ['undo', ['undo']], //撤销
                    ['redo', ['redo']], //取消撤销
                    ['help', ['help']], //帮助
                ],
                callbacks: {
                    onImageUpload: function (files, editor, $editable) {
                        Utils.sendFile(files[0], editor, $editable);
                    }

                }
            });
        },
        /**
         * summernote上传图片
         * @param file
         * @param editor
         * @param $editable
         */
        sendFile: function (file, editor, $editable) {
            var filename = false;
            try {
                filename = file['name'];
            } catch (e) {
                filename = false;
            }
            if (!filename) {
                $(".note-alarm").remove();
            }
            //以上防止在图片在编辑器内拖拽引发第二次上传导致的提示错误
            var ext = filename.substr(filename.lastIndexOf("."));
            ext = ext.toUpperCase();// 验证图片类型
            var timestamp = new Date().getTime();
            var name = timestamp + "_" + $("#summernote").attr('aid') + ext;
            //name是文件名，自己随意定义，aid是我自己增加的属性用于区分文件用户
            var data = new FormData();
            data.append("file", file);
            data.append("key", filename);
            data.append("token", $("#summernote").attr('token'));
            $.ajax({
                data: data,
                async: false,
                type: "POST",
                url: constant.server_path + "/summerNote/picture/upload", //图片上传出来的url，返回的是图片上传后的路径，http格式
                contentType: false,
                cache: false,
                processData: false,
                xhrFields: {
                    withCredentials: true
                },
                success: function (data) {
                    const res = eval("(" + data + ")").resultData;
                    $('#articleContent').summernote('insertImage', constant.img_path + res.pictureUrl, res.name);
                    $("img").addClass("img-responsive center-block");
                },
                error: function () {
                    layer.msg("上传失败！", {time: 1000, icon: 2});
                }
            });
        },

//把一个对象格式化为url路径中能用的参数格式
        formatParams: function (obj) {
            obj = $.extend(obj, constant.commonParams);
            var arr = [];
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    for (var i = 0; i < obj[key].length; i++) {
                        arr.push(key + "=" + obj[key][i]);
                    }
                } else {
                    arr.push(key + "=" + obj[key]);
                }
            }
            return arr.join("&");
        }
        ,

        enCrypt: function (password) {
            if (!password) {
                layer.msg("密码不能为空", {time: 800, icon: 2});
            }
            return $.md5(password);
        }
        ,

        /**
         * 验证输入框不能为空
         * @param text 这是验证的内容
         * @return boolean
         */
        isNull: function (text, required) {
            return (typeof required == 'undefined' ? false : (required == 'required' && !text) ? true : false);
        }
        ,

        /**
         * 验证手机号
         * @param text 这是验证的内容
         * @return boolean
         */
        validPhone: function (text) {
            var reg = /^1(3|4|5|7|8)\d{9}$/;
            return reg.test(text);
        }
        ,

        /**
         * 验证邮箱
         * @param text
         * @return {boolean}
         */
        validEmail: function (text) {
            var reg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
            return reg.test(text);
        }
        ,

        /**
         * 验证邮箱
         * @param text
         * @return {boolean}
         */
        validUrl: function (text) {
            var reg = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/;
            return reg.test(text);
        }
        ,

        /**
         * 验证表单的input select 等
         * @param elements
         */
        validForm: function (elements) {
            var flag = true;
            if (!elements || elements <= 0) {
                layer.msg("表单为空，无法提交", {time: 1000, icon: 2});
                return false;
            }
            $(elements).each(function () {
                const type = $(this).attr("type");
                const required = $(this).attr("required");
                const value = $(this).val();
                const placeholder = $(this).attr("placeholder");
                if (Utils.isNull(value, required)) {
                    layer.msg(placeholder + "不能为空", {time: 1000, icon: 2});
                    flag = false;
                    return;
                }
                if ((type == 'email' && !Utils.validEmail(value)) ||
                    (type == 'tel' && !Utils.validPhone(value)) ||
                    (type == 'url' && !Utils.validUrl(value))
                ) {
                    layer.msg(placeholder + "不符合规则", {time: 1000, icon: 2});
                    flag = false;
                    return;
                }
            });
            return flag;
        },
        logout: function () {
            Utils.getSimpleJson({
                url: "/core/user/logout",
                fn: function () {
                    layer.msg("请登录后访问", {time: 2000, icon: 2}, function () {
                        window.location.href = "login.html";
                    });
                }
            })
        },

        getSearchParams: function (me, url) {
            var params = {};
            const forms = $("#tableInfo").find(".form-control");
            $(forms).each(function () {
                let val = $(this).is("input") ? ($(this).val()) : ($(this).find("option:selected").val());
                params[$(this).attr("cname")] = val;
            })
            if (me) {
                const cval = $(me).attr("cval");
                let temPage = $(me).attr("page");
                if ((temPage && temPage == constant.page) || ((!temPage || temPage == 'undefined') && constant.page > 0)) {
                    constant.page = constant.page;
                } else if (temPage && temPage != constant.page) {
                    constant.page = temPage;
                } else {
                    constant.page = 10;
                }
                params['pageNo'] = cval && cval > 0 ? cval : 1;
                params['pageSize'] = constant.page;
            } else {
                params['pageNo'] = 1;
                params['pageSize'] = 10;
            }
            return params;
        },

        noPre: function () {
            layer.msg("当前是第一页", {time: 1000, icon: 2});
        },

        noNext: function () {
            layer.msg("当前是最后一页", {time: 1000, icon: 2});
        },

        commonInit: function () {
            Utils.logOut();
            Utils.cflagClick();
            Utils.getHeaders();
            Utils.loadPage();
        }
    }
;

window.Utils = Utils;
Utils.commonInit();